//
//  MNDSign.m
//  minidai
//
//  Created by Steven.Yung on 2017/5/4.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDSign.h"
#import "EncryptAddition.h"
#import "NSString+JKBase64.h"
#import "NSDictionary+JKJSONString.h"

static NSTimeInterval preTimeStamp;

@implementation MNDSign

+ (NSDictionary *)signedParam {
    
    return @{@"param" : [MNDSign signParamWithObj:nil]};
}

+ (NSDictionary *)signedParamWithDict: (NSDictionary *)dict {
    return @{@"param" : [MNDSign signParamWithObj:dict]};
}

+ (NSString *)signParamWithObj:(NSDictionary *)obj {
    //    NSString *signStr;
    NSTimeInterval timeInterval = [[NSDate date] timeIntervalSince1970] * 1000;
    NSString *timestamp = [NSString stringWithFormat:@"%ld", (long)timeInterval];
    NSDictionary *appkey = [UserDefaultsTool objectForKey:@"AppKey"];
    
    //避免前后请求时间相同，出现服务器拒绝请求的问题
    if (!preTimeStamp && timeInterval == preTimeStamp) {
        [NSThread sleepForTimeInterval:0.01];
        timeInterval = [[NSDate date] timeIntervalSince1970] * 1000;
        timestamp = [NSString stringWithFormat:@"%ld", (long)timeInterval];
    }
    
    preTimeStamp = timeInterval;
    
    if (!appkey) {
        appkey =  @{@"appkey": @"56934e2667e58e69d000090f", @"appsecret": @"yrjcv3oizcmoztmxmlbrr009q7k6w8rl"};
    }
    //排序
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:obj];
    [dict addEntriesFromDictionary:@{@"version": kAPI_Version}];
    NSArray *sortedKeys = [dict.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2];
        
    }];
    //按参数拼装字符串
    NSMutableString *preSignStr = [NSMutableString string];

    if (dict.count > 0) {
        for (NSString *key in sortedKeys) {
            NSString *param = [NSString stringWithFormat:@"%@=%@", key, dict[key]];
            [preSignStr appendString:param];
            [preSignStr appendString:@"&"];
        }
    }
    
    [preSignStr appendFormat:@"secret=%@&timestamp=%@", appkey[@"appsecret"], timestamp];
    
//    NSLog(@"prestring: %@", preSignStr);
    //参数拼装成字典
    NSDictionary *dic = @{@"key": appkey[@"appkey"],
                          @"timestamp": timestamp,
                          @"sign": [[MD5Util MD5WithString:preSignStr] uppercaseString]};
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    if (dict.count > 0) {
        [params addEntriesFromDictionary:dict];
    }
    [params addEntriesFromDictionary:dic];
    
    NSString *jsonString = [params jk_JSONString];
//    NSLog(@"params: %@", jsonString);
//    NSString *encodeStr = [jsonString jk_base64EncodedString];
//    NSLog(@"params: %@", encodeStr);
    return [jsonString jk_base64EncodedString];
}

/**
 对字典(Key-Value)排序 区分大小写
 
 @param dict 要排序的字典
 */
- (NSArray *)sortedDictionary:(NSDictionary *)dict{
    
    //将所有的key放进数组
    NSArray *allKeyArray = [dict allKeys];
    //序列化器对数组进行排序的block 返回值为排序后的数组
    NSArray *afterSortKeyArray = [allKeyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        /**
         In the compare: methods, the range argument specifies the
         subrange, rather than the whole, of the receiver to use in the
         comparison. The range is not applied to the search string.  For
         example, [@"AB" compare:@"ABC" options:0 range:NSMakeRange(0,1)]
         compares "A" to "ABC", not "A" to "A", and will return
         NSOrderedAscending. It is an error to specify a range that is
         outside of the receiver's bounds, and an exception may be raised.
         
         - (NSComparisonResult)compare:(NSString *)string;
         
         compare方法的比较原理为,依次比较当前字符串的第一个字母:
         如果不同,按照输出排序结果
         如果相同,依次比较当前字符串的下一个字母(这里是第二个)
         以此类推
         
         排序结果
         NSComparisonResult resuest = [obj1 compare:obj2];为从小到大,即升序;
         NSComparisonResult resuest = [obj2 compare:obj1];为从大到小,即降序;
         
         注意:compare方法是区分大小写的,即按照ASCII排序
         */
        //排序操作
        NSComparisonResult resuest = [obj1 compare:obj2];
        return resuest;
    }];
    NSLog(@"afterSortKeyArray:%@",afterSortKeyArray);
    
    //通过排列的key值获取value
    NSMutableArray *valueArray = [NSMutableArray array];
    for (NSString *sortsing in afterSortKeyArray) {
        NSString *valueString = [dict objectForKey:sortsing];
        [valueArray addObject:valueString];
    }
    
    return valueArray;
}

@end
